package com.zjx.reggie.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zjx.reggie.common.CustomException;
import com.zjx.reggie.domain.Setmeal;
import com.zjx.reggie.domain.SetmealDish;
import com.zjx.reggie.dto.SetmealDto;
import com.zjx.reggie.mapper.SetmealMapper;
import com.zjx.reggie.service.SetmealDishService;
import com.zjx.reggie.service.SetmealService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class SetmealServiceImpl extends ServiceImpl<SetmealMapper, Setmeal> implements SetmealService {

    @Autowired
    private SetmealDishService setmealDishService;

    @Transactional
    public void setmealWithDish(SetmealDto setmealDto) {

        //思路分析：1.新增套餐基础信息表 2.套餐与菜品关系表
        //存储新增菜品的基本信息
        this.save(setmealDto);

        //保存套餐与菜品的关联信息
        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();
        setmealDishes.stream().map((item) -> {
            item.setSetmealId(setmealDto.getId());
            return item;
        }).collect(Collectors.toList());
        setmealDishService.saveBatch(setmealDishes);
    }


    /**
     * 删除套餐，同时需要删除套餐与菜品的关联
     *
     * @param ids
     */
    @Transactional
    public void deleteWithDish(List<Long> ids) {
        //查询套餐的售卖状态
        LambdaQueryWrapper<Setmeal> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.in(Setmeal::getId, ids).eq(Setmeal::getStatus, 1);
        int count = this.count(lambdaQueryWrapper);
        if (count > 0) {
            throw new CustomException("套餐正在出售，不能删除");
        }

        //如果可以删除，删除套餐表
        this.removeByIds(ids);

        //删除套餐与菜品的关系表中的数据
        LambdaQueryWrapper<SetmealDish> lambdaQueryWrapper1=new LambdaQueryWrapper<>();
        lambdaQueryWrapper1.in(SetmealDish::getSetmealId,ids);
        setmealDishService.remove(lambdaQueryWrapper1);
    }
}